package com.nhn.android.samples.webview;



import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.HttpAuthHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.eventpopup.R;

public class InAppWebViewControl extends LinearLayout {

	
	public InAppWebViewControl(Context context) {
		super(context);
		mContext = context;
		LayoutInflater inflater =  (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		mMainView = inflater.inflate(R.layout.webview_layout, this);
		mTitle = (TextView)mMainView.findViewById(R.id.oauth_title);
		mCloseButton = (ImageView)mMainView.findViewById(R.id.oauth_close_button);
		mCloseButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				if (mListener != null) {
					mListener.onClick(v);
				}
			}
		});
		
		initWebView();
		// TODO Auto-generated constructor stub
	}
	
	public InAppWebViewControl(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		LayoutInflater inflater =  (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
		mMainView = inflater.inflate(R.layout.webview_layout, this);
		initWebView();
		// TODO Auto-generated constructor stub
	}
	

	public Context mContext = null;
	private View mMainView = null;
	private WebView mWebView;
	private TextView mTitle = null;
	private ImageView mCloseButton = null;
	
	private DialogButtonClickListener mListener= null;
	
	private ProgressBar webviewProgressbar;
	
	Handler completeListener = null;

	public void setButtonClickListener(DialogButtonClickListener listener ) {
		mListener = listener;
	}
	
	public void initWebView() {
		mWebView = (WebView)mMainView.findViewById(R.id.webview_control);

		setWebSettings();
		setBehaviors();
		
		//webviewProgressbar = (ProgressBar)findViewById(R.id.progressBar);
		//webviewProgressbar.setVisibility(View.GONE);

	}
	
	public void setJobCompleteListener (Handler handler) {
		completeListener = handler;
	}
	
	public void setWebSettings() {
		WebSettings ws = mWebView.getSettings();
		ws.setJavaScriptEnabled(true);
		ws.setBuiltInZoomControls(true);
		//ws.setDefaultZoom(ZoomDensity.CLOSE);
		
		ws.setUseWideViewPort(true);
		
		ws.setSavePassword(false); // save 여부를 묻는 창을 나오지 않도록 수정하였다. 위치정보동의에서 주민번호 뒷자리 부분이 password 속성 창이라, 주민번호입력창인데 패스워드를 저장하겠냐고 나오기 때문이다.
		ws.setDefaultTextEncodingName("EUC-KR"); //meta-encoding 이 없는 페이지는 EUC-KR로 표시한더.
		ws.setLoadWithOverviewMode(true); //MOBILESEARCH-2432 항상 전체 화면으로 보이도록

		//ws.setAllowFileAccess(true);
		ws.setPluginsEnabled(true);
		ws.setLightTouchEnabled(true);
		ws.setDomStorageEnabled(true); // 네이버 서비스에서 HTML5 DOM Storage를 사용한다. 20110826 
		//ws.setGeolocationEnabled(true);
		
		if (Build.VERSION.SDK_INT < 8) {
			ws.setPluginsEnabled(true);
		} else {
			ws.setPluginState(WebSettings.PluginState.ON);
		}
	}
	
	public void setBehaviors() {
		mWebView.setVerticalScrollbarOverlay(true);
		mWebView.setHorizontalScrollbarOverlay(true);
		
		mWebView.setWebViewClient(new InAppWebViewClient());
		mWebView.setWebChromeClient(new InAppWebChromeClient());
		mWebView.setDownloadListener(mDefaultDownloadListener);
		mWebView.loadUrl("about:blank");
	}
	
	public void loadUrl(final String url) {
		new Handler().post(new Runnable() {
			
			public void run() {
				mWebView.loadUrl(url);
			}
		});
		
	}
	
	private String mOauthToken= "";
	private String mOauthPIN= "";
	
	//oauth_verifier값을 확인한다.
	public boolean isMatchedAuthorization(String urlString) {
		try {
			if (urlString.startsWith("https://nid.naver.com/") == false) {
				return false;
			}
			
			URL url = new URL(urlString);

			Map<String, String> querymap =	getQueryMap(url.getQuery());
			if (querymap != null && querymap.containsKey("oauth_token") && querymap.containsKey("oauth_verifier") ) {
				mOauthToken = querymap.get("oauth_token");
				mOauthPIN = querymap.get("oauth_verifier");
				return true;
			}
		} catch (MalformedURLException e) {
			
			//e.printStackTrace();
		}
		return false;
		
	}
	
	public boolean loadBrowser(String url) {
		if (url.length() <= 0 || url.contentEquals("about:blank")) {
			return false;
		} else if (url.startsWith("https://nid.naver.com/nidlogin.login") || 
				url.startsWith("https://nid.naver.com/naver.oauth") || 
				url.startsWith("https://nid.naver.com/nidlogin.logout")){
			return false;
		} 
		else if (url.startsWith("http://cc.naver.com") || url.startsWith("http://cr.naver.com")) {
			return false;
		}
		
		return true;
		
		
	}
	
	public static Map<String, String> getQueryMap(String query)  
	{  
		if (query == null){
			return null;
		}
	    String[] params = query.split("&");  
	    Map<String, String> map = new HashMap<String, String>();  
	    for (String param : params)  
	    {  
	        String name = param.split("=")[0];  
	        String value = param.split("=")[1];  
	        map.put(name, value);  
	    }  
	    return map;  
	}  
	
	

	public class InAppWebChromeClient extends WebChromeClient {
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			if (webviewProgressbar != null) {
				webviewProgressbar.setProgress(newProgress);
			}
		}
	}
	
	public class InAppWebViewClient extends WebViewClient {

		@Override
		public void onReceivedHttpAuthRequest(WebView view,
				HttpAuthHandler handler, String host, String realm) {
			// TODO Auto-generated method stub
			super.onReceivedHttpAuthRequest(view, handler, host, realm);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (isMatchedAuthorization(url)) {
				
				Message message = new Message();
				message.what = 100;
				message.obj = mOauthPIN;
				if (completeListener != null) {
					completeListener.sendMessage(message);
				}

				return;
			}

			
			super.onPageStarted(view, url, favicon);
			if (webviewProgressbar != null) {
				webviewProgressbar.setVisibility(View.VISIBLE);
			}

		}

		@Override
		public void onPageFinished(WebView view, String url) {
			
			super.onPageFinished(view, url);
			if (webviewProgressbar != null) {
				webviewProgressbar.setVisibility(View.GONE);
			}

		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			if (webviewProgressbar != null) {
				webviewProgressbar.setVisibility(View.GONE);
			}
			super.onReceivedError(view, errorCode, description, failingUrl);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (loadBrowser(url) == true) {
				
				Intent i = new Intent(Intent.ACTION_VIEW); 
				Uri u = Uri.parse(url); 
				i.setData(u); 
				mContext.startActivity(i);

				return true;
			}
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onFormResubmission(WebView view, final Message dontResend, final Message resend) {
			super.onFormResubmission(view, dontResend, resend);
		}
	}
	
	final DownloadListener mDefaultDownloadListener = new DownloadListener() {
		public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
			/* test required */
			Intent viewIntent = new Intent(Intent.ACTION_VIEW);

			viewIntent.setDataAndType(Uri.parse(url), mimetype);

			try {
				mContext.startActivity(viewIntent); //caution : In case of the context not being attached a activity, this is useless
			} catch (Throwable th) {
				th.printStackTrace();
				try {
					viewIntent.setData(Uri.parse(url));
					mContext.startActivity(viewIntent);
				} catch (Exception ex) {
				}
			}
		}
	};
	
}
